package org.example.xiaomi.controller;

import com.alibaba.fastjson.JSON;
import org.example.xiaomi.dao.impl.CategoryServiceImpl;
import org.example.xiaomi.entity.Category;
import org.example.xiaomi.service.CategoryService;
import org.example.xiaomi.util.HttpResponseUtil;
import org.example.xiaomi.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@WebServlet("/category/list")
public class CategoryListController extends HttpServlet {
    private CategoryService categoryService = new CategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 接收参数
        int page = Integer.parseInt(req.getParameter("page")==null?"1":req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit")==null?"1":req.getParameter("limit"));
        //把json字符串转为Map
        String searchParams = req.getParameter("searchParams");
        Map<String ,Object> searchMap = JSON.parseObject(searchParams, Map.class);
        //2 调用业务逻辑
        List<Category> categoryList = categoryService.getCategoryList( page,limit,searchMap);
        long count = categoryService.getCategoryCount(searchMap);
        //3 生成json格式交换数据
        HttpResponseUtil.response(resp,ResultVO.success(categoryList,count));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
